package com.itrui.socketss;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) throws IOException {
        //连接服务端 (ip , 端口）
        //解读:连接本机的 8888端口, 如果连接成功，返回Socket对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost.toString());
        Socket socket = new Socket(localHost, 8888);
        System.out.println("客户端 连接端口:" + socket.getPort());


        File[] files = createFile("D:\\RuiProject\\FileTest", getFileName("D:\\RuiProject\\FileTest")); //文件夹下的文件

        sendFile(socket, files);

    }

    public static String[] getFileName(String path) {
        File file = new File(path);
        return file.list();
    }

    public static File[] createFile(String path, String[] pathnames) {
        File[] files = new File[pathnames.length];
        try {
            for (int i = 0; i < pathnames.length; i++) {
                File file = new File(path + "\\" + pathnames[i]);
                if (file.exists() && file.isFile()) {
                    file.createNewFile();
                    files[i] = file;
                }
            }
            return files;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;
    }

    public static void sendFile(Socket socket, File[] files) {
        long totalSize = 0;
        byte buf[] = new byte[8192];
        int len;
        try {
            if (socket.isOutputShutdown()) {
                return;
            }
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());

            dout.writeInt(files.length);//文件个数

            for (int i = 0; i < files.length; i++) {
                dout.writeUTF(files[i].getName()); //文件名字
                dout.flush();

                dout.writeLong(files[i].length()); //文件大小
                dout.flush();

                totalSize += files[i].length(); //文件总长度
            }

            dout.writeLong(totalSize);

            for (int i = 0; i < files.length; i++) {
                BufferedInputStream din = new BufferedInputStream(new FileInputStream(files[i]));

                while ((len = din.read(buf)) != -1) {
                    dout.write(buf, 0, len);
                }

                System.out.println("正在传输第" + i + "个文件...");
                Thread.sleep(3000);
            }

            System.out.println("文件传输完成");

        } catch (Exception e) {
            e.printStackTrace();
            //Log.d(TAG,"send file exception");
            System.out.println("send file exception!");
            System.out.println("文件发送错误！");
        }

    }
}
